/**
 * 字体预加载工具
 * @author Wu.Liang
 * @date 2025-01-30
 * @description 在页面头部添加字体预加载链接，优化字体加载性能
 */

/**
 * 添加字体预加载链接
 */
export function addFontPreloadLinks() {
  // 检查是否已经添加过预加载链接
  if (document.querySelector('link[rel="preload"][as="font"][href*="alicdn"]')) {
    return
  }

  // 创建字体预加载链接
  const fontPreloadLink = document.createElement('link')
  fontPreloadLink.rel = 'preload'
  fontPreloadLink.as = 'font'
  fontPreloadLink.type = 'font/ttf'
  fontPreloadLink.crossOrigin = 'anonymous'
  fontPreloadLink.href = 'https://at.alicdn.com/t/font_2225171_8kdcwk4po24.ttf'
  
  // 添加到head标签
  document.head.appendChild(fontPreloadLink)
  
  console.log('字体预加载链接已添加')
}

/**
 * 添加字体样式链接
 */
export function addFontStyleLink() {
  // 检查是否已经添加过样式链接
  if (document.querySelector('link[href*="alicdn"][rel="stylesheet"]')) {
    return
  }

  // 创建字体样式链接
  const fontStyleLink = document.createElement('link')
  fontStyleLink.rel = 'stylesheet'
  fontStyleLink.href = 'https://at.alicdn.com/t/font_2225171_8kdcwk4po24.css'
  
  // 添加到head标签
  document.head.appendChild(fontStyleLink)
  
  console.log('字体样式链接已添加')
}

/**
 * 初始化字体预加载
 */
export function initFontPreload() {
  try {
    addFontPreloadLinks()
    addFontStyleLink()
    console.log('字体预加载初始化完成')
  } catch (error) {
    console.warn('字体预加载初始化失败:', error)
  }
}

/**
 * 动态加载字体样式
 */
export function loadFontStyle() {
  return new Promise((resolve, reject) => {
    const link = document.createElement('link')
    link.rel = 'stylesheet'
    link.href = 'https://at.alicdn.com/t/font_2225171_8kdcwk4po24.css'
    
    link.onload = () => {
      console.log('字体样式加载成功')
      resolve(true)
    }
    
    link.onerror = () => {
      console.warn('字体样式加载失败')
      reject(new Error('字体样式加载失败'))
    }
    
    document.head.appendChild(link)
  })
}

export default {
  addFontPreloadLinks,
  addFontStyleLink,
  initFontPreload,
  loadFontStyle
}
